﻿using System;
using System.IO;
using System.Text;

namespace WebCrawler
{
    public interface IUrlLogger
    {
        void Start();
        void WriteLine(string url);
        void Stop();
    }

    public class UrlLogger : IUrlLogger
    {
        private readonly IFileManager _fileManager;
        protected int _currentSize;
        private StringBuilder _buffer;
        protected int _fileNumber;

        public int FileSize { get; set; }
        public string LogDirectory { get; set; }

        public UrlLogger(IFileManager fileManager)
        {
            _fileManager = fileManager;
        }

        public void Start()
        {
            _currentSize = 0;
            _fileNumber = 0;
            _buffer = new StringBuilder();
        }

        public void WriteLine(string url)
        {
            if (_currentSize + url.Length > FileSize)
                StartNew(url);
            else
            {
                _buffer.AppendLine(url);
                _currentSize += url.Length;
            }
        }

        private void StartNew(string url)
        {
            WriteFile(_buffer.ToString());
            ++_fileNumber;
            _buffer = new StringBuilder(url);
            _currentSize = url.Length;
        }

        public void Stop()
        {
            WriteFile(_buffer.ToString());
            
            _buffer = new StringBuilder();
            _currentSize = 0;
        }

        private void WriteFile(string text)
        {
            var fileName = string.Format("log{0}_{1}.txt", DateTime.Now.ToString("yyyyMMdd"), _fileNumber);
            _fileManager.CreateFile(Path.Combine(LogDirectory,fileName), text);
        }
    }
}